package spring.cloud.service.task.analyzer;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.service.task.service.TaskService;
import spring.cloud.tasks.common.curator.Curator;
import spring.cloud.tasks.common.curator.CuratorInfo;
import spring.cloud.tasks.common.nodepaths.RenewalNodePaths;
import spring.cloud.tasks.common.nodepaths.TaskItemNodePaths;
import spring.cloud.tasks.common.task.TaskItemExecuteRenewalInfo;
import spring.cloud.tasks.common.task.TaskItemRenewalNodeInfo;

import java.util.List;

@Slf4j
@Setter
@Getter
public class OutdatedNoRunningTaskAnalyzer {
    private TaskService taskService;


    public void analyzeOutdatedNoRunningTask(CuratorInfo curatorInfo, Curator curator, List<OutdatedNoRunningTaskTask> outdatedNoRunningTaskTaskList, String taskId) {
        OutdatedNoRunningTaskTask outdatedNoRunningTaskTask = new OutdatedNoRunningTaskTask(curatorInfo.getNamespaceKey(), taskId);

        checkOutdatedNoRunningJob(curator, outdatedNoRunningTaskTaskList, outdatedNoRunningTaskTask);
    }

    private void checkOutdatedNoRunningJob(Curator curator, List<OutdatedNoRunningTaskTask> outdatedNoRunningTaskTaskList, OutdatedNoRunningTaskTask outdatedNoRunningTaskTask) {
        try {
            List<String> taskItemIndexPathList = TaskItemNodePaths.getTaskItemPathList(curator, outdatedNoRunningTaskTask.getTaskId());
            if (taskItemIndexPathList != null) {
                for (String taskItemIndexPath : taskItemIndexPathList) {
                    TaskItemExecuteRenewalInfo taskItemExecuteRenewalInfo = RenewalNodePaths.getTaskItemExecuteRenewalInfo(curator, taskItemIndexPath);
                    if (taskItemExecuteRenewalInfo == null) {
                        TaskItemRenewalNodeInfo taskIdAndTaskInstanceIdAndTaskTurnIdAndTaskItemIndex = new TaskItemRenewalNodeInfo();
                        outdatedNoRunningTaskTask.getTaskIdAndTaskInstanceAndTaskItemList().add(taskIdAndTaskInstanceIdAndTaskTurnIdAndTaskItemIndex);
                    }
                }

            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


}
